<script lang="ts" setup>
import { ref, createVNode } from 'vue'
import { addMenuApi, updateMenuApi, selectMenuAllApi, deleteMenuApi } from '@/api'
import type { FormItem } from '@/interfaces/components/dataForm'
import type { DataFormType, ModalMakeType } from '@/interfaces/components'
import { useCreateInput, useCreateTreeSelect } from '@/hooks/renderHook'
import type { MenuStateNoChildren, SelectMenuAllParams } from '@/interfaces/api/menu'
import { useCreateAiction } from '@/hooks/tableHooks'
import { renderIconKey } from '@/utils/tools'
import store from '@/store'
import { AddSharp } from '@vicons/ionicons5'
import IconSelector from '@/components/IconSelectOr/index'
import useRequest from '@/hooks/requestHooks'

const requestUtils = useRequest()
const tableLoding = ref(false)
/**
 * @description: 表数据
 */
const tableData = ref<MenuStateNoChildren[]>([])

const modalMakeRef = ref<null | ModalMakeType>(null)
const searchForm = ref<null | DataFormType>(null)
const modalForm = ref<null | DataFormType>(null)
const ModalFunction = ref<{ node: 'add' | 'update' | ''; id: number }>({
  node: 'add',
  id: 0,
})

const tableColumn = ref([
  {
    title: '菜单标题',
    key: 'title',
  },
  {
    title: '菜单名称',
    key: 'menuName',
  },
  {
    title: '组件地址',
    key: 'componentPath',
  },
  {
    title: '图标',
    key: 'iocn',
    render(row: MenuStateNoChildren) {
      return renderIconKey(row.iocn, '25px')
    },
  },
  {
    title: '路由地址',
    key: 'path',
  },
  {
    title: '重定向',
    key: 'redirect',
  },
  // {
  //   title: '排序',
  //   key: 'menuOrder',
  // }∏
  {
    title: '操作',
    render(row: MenuStateNoChildren) {
      return useCreateAiction([
        {
          label: '编辑',
          type: 'info',
          disabled: ref(false),
          async onClick(aicItem) {
            await modalMakeRef.value?.show()
            ModalFunction.value.node = 'update'
            ModalFunction.value.id = row.id
            modalForm.value?.update(row)
          },
        },
        {
          label: '删除',
          type: 'error',
          disabled: ref(false),
          onClick(aicItem) {
            store.state.dialog?.warning({
              title: '警告',
              content: '你确定？',
              positiveText: '确定',
              negativeText: '不确定',
              onPositiveClick: async () => {
                await deleteMenuApi({
                  id: row.id,
                })
                getTableData()
              },
            })
          },
        },
      ])
    },
  },
])

const dataFormOptions: Array<FormItem> = [
  {
    label: '菜单标题',
    key: 'title',
    value: ref(''),
    render(formTtem) {
      return useCreateInput({
        inputPropsOptions: {
          size: 'small',
          placeholder: '请输入菜单标题',
        },
        refState: formTtem.value,
      })
    },
  },
  {
    label: '菜单名称',
    key: 'menuName',
    value: ref(''),
    render(formTtem) {
      return useCreateInput({
        inputPropsOptions: {
          size: 'small',
          placeholder: '请输入菜单名称',
        },
        refState: formTtem.value,
      })
    },
  },
]

/**
 * @description: 筛选表单的搜索按钮
 */
const searchTableData = () => {
  const params = searchForm.value?.generatorParams() as SelectMenuAllParams
  getTableData(params)
}

/**
 * @description: 筛选表单的重置按钮
 */
const resetSearch = () => {
  searchForm.value?.reset()
}

/**
 * @description: 获取表格数据
 */
const getTableData = async (data: SelectMenuAllParams = { title: '', menuName: '' }) => {
  await requestUtils.useLoadingRequestOrIsNull<MenuStateNoChildren>({
    axios: selectMenuAllApi(data),
    loadings: [tableLoding],
    state: tableData,
  })
}
getTableData()

const modalFormOptions: Array<FormItem> = [
  {
    label: '上级菜单',
    key: 'parentId',
    value: ref(''),
    required: true,
    render(formTtem) {
      return useCreateTreeSelect({
        treeSelectOptions: [
          {
            label: '主菜单',
            id: -1,
          },
          ...(store.state.menuList as any[]),
        ],
        treeSelectPropsOptions: {
          size: 'small',
          placeholder: '请输入上级菜单',
          keyField: 'id',
        },
        refState: formTtem.value,
      })
    },
  },
  {
    label: '菜单标题',
    key: 'title',
    value: ref(''),
    required: true,
    render(formTtem) {
      return useCreateInput({
        inputPropsOptions: {
          size: 'small',
          placeholder: '请输入菜单标题',
        },
        refState: formTtem.value,
      })
    },
  },
  {
    label: '菜单名称',
    key: 'menuName',
    value: ref(''),
    required: true,
    render(formTtem) {
      return useCreateInput({
        inputPropsOptions: {
          size: 'small',
          placeholder: '请输入菜单名称',
        },
        refState: formTtem.value,
      })
    },
  },
  {
    label: '组件地址',
    key: 'componentPath',
    value: ref(''),
    render(formTtem) {
      return useCreateInput({
        inputPropsOptions: {
          size: 'small',
          placeholder: '请输入组件地址',
        },
        refState: formTtem.value,
      })
    },
  },
  {
    label: '菜单图标',
    key: 'iocn',
    required: true,
    value: ref(''),
    render(formTtem) {
      return createVNode(IconSelector, {
        defaultValue: formTtem.value.value,
        onUpdateValue(value: string) {
          formTtem.value.value = value
        },
      })
    },
  },
  {
    label: '路由地址',
    key: 'path',
    value: ref(''),
    required: true,
    render(formTtem) {
      return useCreateInput({
        inputPropsOptions: {
          size: 'small',
          placeholder: '请输入组件地址',
        },
        refState: formTtem.value,
      })
    },
  },
  {
    label: '重定向',
    key: 'redirect',
    value: ref(''),
    render(formTtem) {
      return useCreateInput({
        inputPropsOptions: {
          size: 'small',
          placeholder: '请输入组件地址',
        },
        refState: formTtem.value,
      })
    },
  },
  // {
  //   label: '排序',
  //   key: 'menuOrder',
  //   required: true,
  //   value: ref(0),
  //   reset(formTtem) {
  //     formTtem.value.value = 0
  //   },
  //   render(formTtem) {
  //     return useCreateInputNumber({
  //       inputNumberPropsOptions: {
  //         size: 'small',
  //         placeholder: '请输入组件地址',
  //       },
  //       refState: formTtem.value,
  //     })
  //   },
  // },
]

/**
 * @description: 新增按钮触发的方法
 */
const operationModal = async () => {
  await modalMakeRef.value?.show()
  modalForm.value?.reset()
  ModalFunction.value.node = 'add'
}

/**
 * @description: 表单提交，新增/修改表单按钮触发的事件
 */
const confirm = () => {
  // 获取表单的参数
  let params = modalForm.value?.generatorParams()

  if (ModalFunction.value.node === 'update') {
    updateConfirm({ ...params, id: ModalFunction.value.id })
  } else if (ModalFunction.value.node === 'add') {
    addConfirm(params)
  }
}

/**
 * @description: 更新事件
 */
const updateConfirm = async (params: MenuStateNoChildren) => {
  // 验证表单
  if (modalForm.value?.validator()) {
    await updateMenuApi(params)
    await modalMakeRef.value?.colse()
    getTableData()
  }
}

/**
 * @description: 添加事件
 */
const addConfirm = async (params: MenuStateNoChildren) => {
  // 验证表单
  if (modalForm.value?.validator()) {
    await addMenuApi(params)
    await modalMakeRef.value?.colse()
    getTableData()
  }
}
</script>

<template lang="pug">
div(class="animate__animated animate__fadeIn animate__delay-0.7s")
  n-space(vertical)
    n-card(:title="'菜单管理'") 菜单管理,管理左侧导航栏.
    TableBody()
      template(#header) 
        TableHeader(searchContentHeight="200px" @search="searchTableData" @reset-search="resetSearch")
          template(#searchForm)
            DataForm(ref="searchForm" :form-config="{}" :options="dataFormOptions" preset="grid-item")
          template(#rightBtn)
            n-button(size="small" type="info" @click="operationModal") 新增
              template(#icon)
                n-icon
                  AddSharp
      template(#body)
        n-data-table(:single-line="false" :columns="tableColumn" :data="tableData" :loading="tableLoding" :row-key="(row: any) => row.id")
ModalMake(title="菜单控制台" ref="modalMakeRef" contentHeight="20px" @confirm="confirm")
  DataForm(ref="modalForm" :form-config="{}" :options="modalFormOptions" )
</template>

<style lang="scss" scoped>
.mini-height {
  min-height: 115px;
}
</style>
